﻿using UnityEngine;
using System.Collections;

public class BackgroundManager : MonoBehaviour {

    private PlayerManager Player;

    public GameObject Background;
    public GameObject BgSwitchObject;
    private Vector3 BackgroundSwitchSpawnPos = new Vector3(-40, 6.5f, 8);

    // Indicates when the next level change will occur
    private int NextSwitch = 150;
    private int SwitchNumber = 0;

    // The background screen images
    private Sprite[] BackgroundSprites;
    // The images that are used for switching levels
    private Sprite[] SwitchSprites;

    // Indicates that the level switch is starting
    public delegate void StartSwitchAction(string levelIndex);
    public static event StartSwitchAction OnBeginChange;

    // Indicates that a level has changed
    public delegate void ChangeLevelAction(string levelIndex);
    public static event ChangeLevelAction OnChange;

	void Start () {

        // Load all sprites
        BackgroundSprites = Resources.LoadAll<Sprite>("Background/Static");
        SwitchSprites = Resources.LoadAll<Sprite>("Background/Switch");

	}

	void Update () {

        int distance = (int)Player.getDistance();
        
        if (distance > NextSwitch)
        {
            switch (SwitchNumber)
            {
                case 0:
                    NextSwitch += 50;

                    // Create the background switch object
                    GameObject BgSwitch = Instantiate(BgSwitchObject, BackgroundSwitchSpawnPos, Quaternion.identity) as GameObject;
                    
                    // Set the image
                    BgSwitch.GetComponent<SpriteRenderer>().sprite = SwitchSprites[0] as Sprite;

                    // Signal that a level is changing
                    OnBeginChange("1");

                    break;

                case 1:
                    NextSwitch = 999999;

                    // Change the background image
                    Background.GetComponent<SpriteRenderer>().sprite = BackgroundSprites[1] as Sprite;

                    // Signal tat the level has changed
                    OnChange("2");
                    
                    break;

                case 2:
                    break;
            }

            SwitchNumber++;

        }
	
	}

    public void SetMainPlayer(PlayerManager i_Player)
    {
        Player = i_Player;
    }
}
    